#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <fcgi_stdio.h>
#include "register.h"
#include "log.h"
#include "util.h"
#include "cjson.h"
#include "config.h"
#include "kmysql.h"

int GetRegisterInfo(char *RegisterBuf, char *username, char *pwd, char *nickname, char *phone, char *email)
{
    if (NULL == RegisterBuf || NULL == username || NULL == pwd || NULL == nickname || NULL == phone || NULL == email)
    {
        LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "input param error\n");
        return -1;
    }

    int ret = 0;

    cJSON *json = cJSON_Parse(RegisterBuf);
    do
    {
        if (NULL == json)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "cJSON_Parse error\n");
            ret = -1;
            break;
        }

        // 获取用户名
        cJSON *jsonUser = cJSON_GetObjectItem(json, "userName");
        if (NULL == jsonUser)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "cJSON_GetObjectItem error\n");
            ret = -1;
            break;
        }
        strcpy(username, jsonUser->valuestring);

        // 获取密码
        cJSON *jsonPwd = cJSON_GetObjectItem(json, "pwd");
        if (NULL == jsonPwd)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "cJSON_GetObjectItem error\n");
            ret = -1;
            break;
        }
        strcpy(pwd, jsonPwd->valuestring);

        // 昵称
        cJSON *jsonNickname = cJSON_GetObjectItem(json, "nickName");
        if (NULL == jsonNickname)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "cJSON_GetObjectItem error\n");
            ret = -1;
            break;
        }
        strcpy(nickname, jsonNickname->valuestring);

        // 电话
        cJSON *jsonPhone = cJSON_GetObjectItem(json, "phone");
        if (NULL == jsonPhone)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "cJSON_GetObjectItem error\n");
            ret = -1;
            break;
        }
        strcpy(phone, jsonPhone->valuestring);

        // 邮箱
        cJSON *jsonEmail = cJSON_GetObjectItem(json, "email");
        if (NULL == jsonEmail)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "cJSON_GetObjectItem error\n");
            ret = -1;
            break;
        }
        strcpy(email, jsonEmail->valuestring);
    } while (0);

    if (json)
    {
        cJSON_Delete(json);
        json = NULL;
    }

    return ret;
}

int UserRegister(char *RegisterBuf)
{
    if (NULL == RegisterBuf)
    {
        LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "input param error\n");
        return -1;
    }

    MYSQL *conn = NULL;
    int ret = 0;
    char sqlCmd[SQL_MAX_LEN] = {0};
    char mysqlUser[SQL_CONFIG_BUFFER_SIZE] = {0};
    char mysqlPwd[SQL_CONFIG_BUFFER_SIZE] = {0};
    char mysqlDB[SQL_CONFIG_BUFFER_SIZE] = {0};

    ret = GetMysqlInfo(mysqlUser, mysqlPwd, mysqlDB);
    if (ret != 0)
    {
        LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "GetMysqlInfo error\n");
        return -1;
    }

    do
    {
        // 获取注册信息
        char username[128] = {0};
        char pwd[256] = {0};
        char nickname[128] = {0};
        char phone[128] = {0};
        char email[128] = {0};
        ret = GetRegisterInfo(RegisterBuf, username, pwd, nickname, phone, email);
        if (ret != 0)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "GetRegisterInfo error\n");
            ret = -1;
            break;
        }

        conn = MysqlConn(mysqlUser, mysqlPwd, mysqlDB);
        if (NULL == conn)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "MysqlConn error\n");
            ret = -1;
            break;
        }

        mysql_query(conn, "set names utf8");

        char cmdSql[SQL_MAX_LEN] = {0};
        sprintf(cmdSql, "select * from user where name='%s'", username);
        int ret2 = ProcessResultOne(conn, cmdSql, NULL, 0);
        if (2 == ret2) // 用户存在
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "user is exist\n");
            ret = -2;
            break;
        }

        // 获取当前时间
        struct timeval tv;       // 定义一个时间结构体，用于存储当前时间
        struct tm *ptm;          // 定义一个指向时间结构体的指针，用于存储本地时间
        char timeStr[128] = {0}; // 定义一个字符数组，用于存储格式化后的时间字符串

        gettimeofday(&tv, NULL);                                      // 获取当前时间，精确到微秒，存储在tv结构体中
        ptm = localtime(&tv.tv_sec);                                  // 将秒数转换为本地时间，并存储在ptm指针指向的结构体中
        strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", ptm); // 将本地时间格式化为字符串，存储在timeStr数组中
        sprintf(sqlCmd, "insert user_info (user_name, nick_name, password, phone, email, create_time) values('%s', '%s', '%s', '%s', '%s', '%s')", username, nickname, pwd, phone, email, timeStr);
        if (mysql_query(conn, sqlCmd) != 0)
        {
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "mysql_query error, %s\n", mysql_error(conn));
            ret = -1;
            break;
        }
    } while (0);
    if (conn)
    {
        mysql_close(conn);
        conn = NULL;
    }

    return ret;
}

int main()
{
    LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "main  -----------\n");
    while(FCGI_Accept() >= 0)
    {
        char *contentLength = getenv("CONTENT_LENGTH");
        int len = 0;

        printf("Content-type: text/html\r\n\r\n");
        if(contentLength)
            len = atoi(contentLength);

        if(len <= 0)
        {
            printf("No data from standard input.<p>\n");
            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "len = 0, No data from standard input\n");
        }
        else
        {
            // 获取用户的登录信息
            char buf[4 * 1024] = {0};
            //从标准输入(web服务器)读取内容
            int ret = fread(buf, 1, len, stdin);
            if(ret == 0)
            {
                LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "fread(buf, 1, len, stdin) error\n");
                continue;
            }

            LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "buf = %s\n", buf);

            char *out = NULL;
            ret = UserRegister(buf);
            if(0 == ret) 
            {
                // 注册成功
                LOG(REGISTER_LOG_MODULE, REGISTER_LOG_PROC, "register success\n");
                out = ReturnStatus("002");
            }
            else if(-1 == ret)
            {
                // 注册失败
                out = ReturnStatus("004");
            }
            else if(-2 == ret)
            {
                // 用户名已存在
                out = ReturnStatus("003");
            }

            if(NULL != out)
            {
                printf(out);
                FREE(out);
            }
        }
    }

    return 0;
}